package com.btcTool;

public class PrivateKeyFormat extends KeyFormat{

    private String keyType;
    public PrivateKeyFormat(String keyType) {
        if ( keyType == null)
            throw new BtcException("密钥格式不可以为空");
        if ( !PRIV_KEY_HEX.equals(keyType) &&
                !PRIV_KEY_WIF.equals(keyType) &&
                !PRIV_KEY_WIFC.equals(keyType))
            throw new BtcException("不支持的密钥格式");
        this.keyType = keyType;
    }

    /**
     * 未加工的密钥格式化
     */
    @Override
    public String format(byte[] keyBytes) {
        if ( PRIV_KEY_HEX.equals(keyType)) {
            return BtcUtils.toHexString(keyBytes);
        }
        if ( PRIV_KEY_WIF.equals(keyType)) {
            byte version = (byte)0x80;
            return BtcUtils.encode(version, keyBytes);
        }
        if ( PRIV_KEY_WIFC.equals(keyType)) {
            byte[] cBytes = new byte[ keyBytes.length + 1];
            System.arraycopy(keyBytes, 0, cBytes, 0, keyBytes.length);
            cBytes[ cBytes.length - 1] = 0x01;
            byte version = (byte)0x80;
            return BtcUtils.encode(version, cBytes);
        }
        return null;
    }

    @Override
    public byte[] parse(String src) {
        if ( PRIV_KEY_HEX.equals(keyType)) {
            return BtcUtils.hexStringToByte(src);
        }
        if ( PRIV_KEY_WIF.equals(keyType)) {
            return BtcUtils.decode(src);
        }
        if (PRIV_KEY_WIFC.equals(keyType)) {
            byte[] rawBytes = BtcUtils.decode(src);
            byte[] result = new byte[rawBytes.length-1];
            System.arraycopy(rawBytes, 0, result, 0, result.length);
            return result;
        }
        return null;
    }



}
